package com.roc.web.action.terminal;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.page.BaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.YjPosBatch;
import com.roc.service.ITerminalSnBatchSerice;
import com.roc.service.IorgService;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Component
@Scope("prototype")
@Namespace("/terminalSnBatchTxtLeading")
public class TerminalSnBatchTxtLeadingAction extends BaseAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 5839095974243472588L;

	private Logger logger=LogManager.getLogger(TerminalSnBatchTxtLeadingAction.class);

	@Autowired 
	ITerminalSnBatchSerice  terminalSnBatchSerice;
	
	@Autowired
	IorgService orgService;

	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	
	private YjPosBatch yjPosBatch ;
	
//	private String msg;
	
	@Action(value = "terminalSnBatchTxtLeadingJsp", results = { @Result(name = "success", location = "/pages/terminal/terminal_sn_batch_txt_leading.jsp")
             })
	public String terminalSnBatchTxtLeadingJspAction() throws Exception{
		Operators logingOperators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		String loginId = String.valueOf(logingOperators.getId());
		
		if( !logingOperators.getRoleType().equals(Role.SYSTEM.getCode())  
				&& ! loginId.equals(Constant.SHOUDANSHIYEBU_ID)
				&& ! logingOperators.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode()) ) {
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		org();
		return SUCCESS;
	}
	
	@Action(value = "terminalSnBatchTxtLeading", interceptorRefs = {
			@InterceptorRef(value = "token"),
			@InterceptorRef(value = "rocDefaultStack", params = {
					"fileUpload.allowedExtensions", "xlsx",
					"fileUpload.maximumSize", "100000000" }) }, results = { 
			@Result(name = "success", location = "/pages/terminal/terminal_sn_batch_txt_leading.jsp"),
			@Result(name = "error", location = "/error.jsp"),
			@Result(name = "invalid.token", location = "/error.jsp")
	    })
	public String terminalSnBatchTxtLeadingAction() throws Exception{

		Operators loginOperators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);

		String loginId = String.valueOf(loginOperators.getId());
		
		if( !loginOperators.getRoleType().equals(Role.SYSTEM.getCode())  
				&& ! loginId.equals(Constant.SHOUDANSHIYEBU_ID)
				&& ! loginOperators.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode()) ) {
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		
		if(  "".equals(yjPosBatch.getAgentId()) || yjPosBatch.getAgentId() <= 0 ){
			addActionMessage("请选择代理商");
			return ERROR;
		}
		if( null == yjPosBatch.getBeginSerialNum() || "".equals(yjPosBatch.getBeginSerialNum().trim()) ){
			addActionMessage("请输入开始号段");
			return ERROR;
		}
		if( null == yjPosBatch.getEndSerialNum() || "".equals(yjPosBatch.getEndSerialNum().trim()) ){
			addActionMessage("请输入结束号段");
			return ERROR;
		}
		if (!Utils.checkSnCode(yjPosBatch.getBeginSerialNum())) {
			addActionMessage("开始SN号 " + yjPosBatch.getBeginSerialNum() + " 文字格式不对,请重新输入");
			return ERROR;
		}
		if (!Utils.checkSnCode(yjPosBatch.getEndSerialNum())){
			addActionMessage("结束SN号 " + yjPosBatch.getEndSerialNum() + " 文字格式不对,请重新输入");
			return ERROR;
		}
		
		try {
	        // 判断是否是同一个号段
	        boolean flag = getUnContSNInfo(yjPosBatch);
	        if( !flag ){
	        	addActionMessage("导入的sn号号段 不是同一个号段，请确认!");
	        	return SUCCESS;
	        }
	        terminalSnBatchSerice.batchTxtSaveSeriaNumInfo(yjPosBatch, loginOperators);
         
	        String msg = "操作员【"+loginOperators.getAccountNo()+"】成功导入【" + (yjPosBatch.getBeginSerialNum()) + "-" + (yjPosBatch.getEndSerialNum()) +"】 号段";
	        getRequest().setAttribute("msg", msg);
	        org();
        //    addActionMessage("操作员【"+loginOperators.getAccountNo()+"】成功导入【" + (yjPosBatch.getBeginSerialNum()) + "-" + (yjPosBatch.getEndSerialNum()) +"】 号段");
            
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		
		return SUCCESS;
	}

	private boolean getUnContSNInfo( YjPosBatch info){
		boolean flag = false;
		try {
			String beginSn = info.getBeginSerialNum().trim();
			String endSn = info.getEndSerialNum().trim();

			// 第一个SN 的长度,
			int bLength = beginSn.length();
			// 取SN最后一个字符的位置,便于分割
			int bLastChar = Constance.getSNLastCharPlace(beginSn);

			String bChars = getChar(bLastChar, beginSn);
			String bNumber = getSnNumber(bLastChar, beginSn);

			// 最后一个SN 的长度,
			int eLength = endSn.length();
			// 取SN最后一个字符的位置,便于分割
			int eLastChar = Constance.getSNLastCharPlace(endSn);

			String eChars = getChar(eLastChar, endSn);
			String eNumber = getSnNumber(eLastChar, endSn);

			if( bLength == eLength && bLastChar == eLastChar && bChars.equals(eChars) && (
					( ( null == bNumber || "".equals(bNumber) ) && ( null == eNumber || "".equals(eNumber) ) ) 
					|| 
					(  Long.parseLong(bNumber) <= Long.parseLong(eNumber) )
					)  ){
				flag = true;
				if (  ( null == bNumber || "".equals(bNumber) ) && ( null == eNumber || "".equals(eNumber) )  ){
					yjPosBatch.setNums( 1 );
				}else {
					yjPosBatch.setNums(  Integer.parseInt( String.valueOf( Long.parseLong(eNumber) - Long.parseLong(bNumber) ) ) + 1 );
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}
		return flag;
	}

	private String getChar( int lastChar ,String sn ){
		String bChars = "";
		if( lastChar >= 0){
			bChars = sn.substring(0, lastChar + 1);
		}
		return bChars;
	}
	
	private String getSnNumber( int lastChar ,String sn ){
		String bNumber = "";
		if ( lastChar < ( sn.length()-1 ) ){
			bNumber = sn.substring( ( lastChar== -1 ? 0 : lastChar + 1 ), sn.length() );
		}
		return bNumber;
	}
	
	//查询机构
	public void org() throws Exception{
	//	Operators logingOperators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		TblInsInf inf = new TblInsInf();
		orgList=orgService.listOrg(inf);
		
		getRequest().setAttribute("brandMap",ConfigProperties.getSysDB1("TMNL_BRAND",true));
		getRequest().setAttribute("nameMap", new ArrayList<Map<String,Object>>());
		getRequest().setAttribute("typeMap", ConfigProperties.getSysDB1("Terminal_Type",true));	
	}

	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	public YjPosBatch getYjPosBatch() {
		return yjPosBatch;
	}

	public void setYjPosBatch(YjPosBatch yjPosBatch) {
		this.yjPosBatch = yjPosBatch;
	}
/*
	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}
*/
}
